# -*- coding: utf-8 -*-
# @Author: dapan 191042102
# @Date:   2019-11-21 09:52:38
# @Last Modified time: 2020-07-22 10:39:34
from flask import render_template, request, Response, redirect
from . import main
from .. import fun
from .. import db
from app.myclass.dedecms import dedecms
from ..models import Release
from ..models import Releasechild
import requests
import json
from app.myclass.addcount import Addcount

res = requests.session()


@main.route('/release',endpoint='release')
@fun.is_login
def release():
  kw = request.args.get('kw', '', type=str)
  where = []
  if kw:
    where.append(Release.sitename.like("%{}%".format(kw.strip())))
  release = Release.query.filter(*where).all()
  sitelistdata = []
  addcount = Addcount()
  for i in release:
    count = addcount.get(i.id,i.adddate)
    tem = {'id':i.id,'sitename':i.sitename,'typeid':i.typeid,'username':i.username,'addtime':i.addtime,'url':i.url,'count':count}
    sitelistdata.append(tem)
  count = Release.query.filter(*where).count()
  return render_template('release/release.html',data = sitelistdata,count=count,kw=kw)


@main.route('/release_add',endpoint='release_add',methods=['GET', 'POST'])
@fun.is_login
def release_add():
  if request.method == 'GET':
    return render_template('release/release_add.html')
  elif request.method == 'POST':
    sitename = request.form.get('sitename', '', type=str)
    url = request.form.get('url', '', type=str)
    loginurl = request.form.get('loginurl', '', type=str)
    username = request.form.get('username', '', type=str)
    password = request.form.get('password', '', type=str)
    key = request.form.get('key', '', type=str)
    charset = request.form.get('charset', 0, type=int)
    typeid = request.form.get('typeid', 0, type=int)
    if sitename and url and loginurl and username and password and typeid:
      release_db = Release(sitename = sitename , loginurl=loginurl, url = url, username=username, key=key, password=password,typeid=typeid,charset=charset)
      db.session.add(release_db)
      db.session.commit()
      db.session.close()
      return fun.msg_json(1, '添加成功')
    return fun.msg_json(0, 'error')

@main.route('/release_edit/<id>',endpoint='release_edit',methods=['GET','POST'])
@fun.is_login
def release_edit(id):
  if id:
    row = Release.query.filter_by(id=id).first()
    if row:
      if request.method == 'GET':
        return render_template('release/release_edit.html',row=row)
      elif request.method == 'POST':
        row.sitename = request.form.get('sitename', '', type=str)
        row.url = request.form.get('url', '', type=str)
        row.loginurl = request.form.get('loginurl', '', type=str)
        row.username = request.form.get('username', '', type=str)
        row.password = request.form.get('password', '', type=str)
        row.key = request.form.get('key', '', type=str)
        row.typeid = request.form.get('typeid', 0, type=int)
        db.session.commit()
        db.session.close()
        return fun.msg_json(1, '修改成功')

@main.route('/release_del/<id>',endpoint='release_del',methods=['GET'])
@fun.is_login
def release_del(id):
  if request.method == 'GET':
    if id:
      db.session.query(Release).filter_by(id=id).delete()
      db.session.commit()
      db.session.close()
      return fun.msg_json(1, '删除成功')

@main.route('/release_login/<id>',endpoint='release_login',methods=['GET','POST'])
@fun.is_login
def release_login(id):
  row = Release.query.filter_by(id=id).first()
  if row:
    if request.method == 'GET':
      if not row.cookies:
        return render_template('release/release_login.html',row = row)
      dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
      dede.set_cookie(json.loads(row.cookies))
      ischeck = dede.check()
      if ischeck:
        return render_template('release/release_check_success.html')
      if not ischeck and row.key:
        islogin,cookie = dede.login(row.key)
        if islogin and cookie:
          row.cookies = cookie
          db.session.commit()
          db.session.close()
          return render_template('release/release_check_success.html')
      return render_template('release/release_login.html',row = row)
    elif request.method == 'POST':
      username = request.form.get('username','',type=str)
      password = request.form.get('password','',type=str)
      code = request.form.get('verify','',type=str)
      dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
      islogin,cookie = dede.login(code)
      if cookie == 404:
        return fun.msg_json(0, '登录页面未找到，检查登录页面是否正确！')
      if not islogin:
        return fun.msg_json(0, cookie)
      if islogin and cookie:
        row.cookies = cookie
        db.session.commit()
        db.session.close()
        return fun.msg_json(1, '登录成功')
      else:
        return fun.msg_json(0, '登录出错，重新登录试试')

@main.route('/release_list/<id>',endpoint='release_list')
@fun.is_login
def release_list(id):
  row = Release.query.filter_by(id=id).first()
  if not row.cookies:
    return render_template('release/release_login.html',row = row)
  dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
  dede.set_cookie(json.loads(row.cookies))
  ischeck = dede.check()
  if not ischeck:
    if row.key:
      islogin,cookie = dede.login(row.key)

      if islogin and cookie:
          row.cookies = cookie
          db.session.commit()
          db.session.close()
      else:
        return render_template('release/release_login.html',row = row)
    else:
      return render_template('release/release_login.html',row = row)
  artlist = dede.getArtlist()
  if artlist:
    return render_template('release/release_artlist.html',artlist = artlist)
  return 'error'

@main.route('/release_child/<id>',endpoint='release_child',methods=['GET','POST'])
@fun.is_login
def release_child(id):
  if request.method == 'GET':
    row = Release.query.filter_by(id=id).first()
    return render_template('release/release_child.html',row=row)
  elif request.method =='POST':
    sitename = request.form.get('sitename', '', type=str)
    url = request.form.get('url', '', type=str)
    loginurl = request.form.get('loginurl', '', type=str)
    username = request.form.get('username', '', type=str)
    password = request.form.get('password', '', type=str)
    charset = request.form.get('charset', 0, type=int)
    typeid = request.form.get('typeid', 0, type=int)
    pid = request.form.get('pid', 0, type=int)
    if sitename and url and loginurl and username and password and typeid and pid:
      release_db = Releasechild(sitename = sitename , loginurl=loginurl, url = url, username=username, password=password,typeid=typeid,pid=pid,charset=charset)
      db.session.add(release_db)
      db.session.commit()
      db.session.close()
      return fun.msg_json(1, '添加成功')
    return fun.msg_json(0, 'error')

@main.route('/release_child_login/<id>',endpoint='release_child_login',methods=['GET','POST'])
@fun.is_login
def release_child_login(id):
  row = Releasechild.query.filter_by(id=id).first()
  if row:
    if request.method == 'GET':
      if not row.cookies:
        return render_template('release/release_child_login.html',row = row)
      dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
      dede.set_cookie(json.loads(row.cookies))

      ischeck = dede.check()
      if ischeck:
        return render_template('release/release_check_success.html')
      if not ischeck and row.key:
        islogin,cookie = dede.login(row.key)
        if islogin and cookie:
          row.cookies = cookie
          db.session.commit()
          db.session.close()
          return render_template('release/release_check_success.html')
      return render_template('release/release_child_login.html',row = row)

    elif request.method == 'POST':
      username = request.form.get('username','',type=str)
      password = request.form.get('password','',type=str)
      code = request.form.get('verify','',type=str)
      dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
      islogin,cookie = dede.login(code)
      if cookie == 404:
        return fun.msg_json(0, '登录页面未找到，检查登录页面是否正确！')
      if not islogin:
        return fun.msg_json(0, cookie)
      if islogin and cookie:
        row.cookies = cookie
        db.session.commit()
        db.session.close()
        return fun.msg_json(1, '登录成功')
      else:
        return fun.msg_json(0, '登录出错，重新登录试试')

@main.route('/release_child_del/<id>',endpoint='release_child_del')
@fun.is_login
def release_child_del(id):
  if id:
    db.session.query(Releasechild).filter_by(id=id).delete()
    db.session.commit()
    db.session.close()
    return fun.msg_json(1, '成功')

@main.route('/release_makehtml/<id>',endpoint='release_makehtml')
@fun.is_login
def release_makehtml(id):
  if id:
    row = Release.query.filter_by(id=id).first()
    dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
    dede.set_cookie(json.loads(row.cookies))

    ischeck = dede.check()
    if not ischeck:
      if row.key:
        islogin,cookie = dede.login(row.key)
        if islogin and cookie:
            row.cookies = cookie
            db.session.commit()
            db.session.close()
        else:
          return fun.msg_json(0, '该网站Cookie已失效，请登录！')
      else:
        return fun.msg_json(0, '该网站Cookie已失效，请登录！')

    if dede.makeHTML():
      if len(row.child)>0:
        for icild in row.child:
          dedechild = dedecms(dedeurl=icild.url+icild.loginurl,session=res,username=icild.username,password=icild.password,code=icild.key,charset=icild.charset)
          
          dedechild.set_cookie(json.loads(icild.cookies))
          if not dedechild.makeHTML():
            return fun.msg_json(0, '子网站生成错误，请到子网站页面处理！')
      return fun.msg_json(1, '首页生成成功')
    else:
      return fun.msg_json(0, '失败')

@main.route('/release_makeRSS/<id>',endpoint='release_makeRSS')
@fun.is_login
def release_makeRSS(id):
  if id:
    row = Release.query.filter_by(id=id).first()
    dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
    dede.set_cookie(json.loads(row.cookies))
    ischeck = dede.check()
    if not ischeck:
      if row.key:
        islogin,cookie = dede.login(row.key)
        if islogin and cookie:
            row.cookies = cookie
            db.session.commit()
            db.session.close()
        else:
          return fun.msg_json(0, '该网站Cookie已失效，请登录！')
      else:
        return fun.msg_json(0, '该网站Cookie已失效，请登录！')
    if dede.makeRSS():
      if len(row.child)>0:
        for icild in row.child:
          dedechild = dedecms(dedeurl=icild.url+icild.loginurl,session=res,username=icild.username,password=icild.password,code=icild.key,charset=icild.charset)
          dedechild.set_cookie(json.loads(icild.cookies))
          if not dedechild.makeRSS():
            return fun.msg_json(0, '子网站RSS生成错误，请到子网站页面处理！')
      return fun.msg_json(1, 'RSS生成成功')
    else:
      return fun.msg_json(0, 'error')

@main.route('/release_makecate/<id>/<page>',endpoint='release_makecate')
@fun.is_login
def release_makecate(id,page):
  row = Release.query.filter_by(id=id).first()
  dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
  dede.set_cookie(json.loads(row.cookies))

  ischeck = dede.check()
  if not ischeck:
    if row.key:
      islogin,cookie = dede.login(row.key)
      if islogin and cookie:
          row.cookies = cookie
          db.session.commit()
          db.session.close()
      else:
        return redirect("/release_login/"+id)
    else:
      return redirect("/release_login/"+id)
  rs = dede.makeCateHtml(page)
  page = int(page)+1
  return render_template('release/release_makecate.html',rs=rs,id=id,page=page)

@main.route('/release_child_makecate/<id>/<page>',endpoint='release_child_makecate')
@fun.is_login
def release_child_makecate(id,page):
  row = Releasechild.query.filter_by(id=id).first()
  dede = dedecms(dedeurl=row.url+row.loginurl,session=res,username=row.username,password=row.password,code=row.key,charset=row.charset)
  dede.set_cookie(json.loads(row.cookies))

  ischeck = dede.check()
  if not ischeck:
    if row.key:
      islogin,cookie = dede.login(row.key)
      if islogin and cookie:
          row.cookies = cookie
          db.session.commit()
          db.session.close()
      else:
        return redirect("/release_child_login/"+id)
    else:
      return redirect("/release_child_login/"+id)

  rs = dede.makeCateHtml(page)
  page = int(page)+1
  return render_template('release/release_child_makecate.html',rs=rs,id=id,page=page)


@main.route('/verify/<id>/',endpoint='verify')
def verify(id):
  if id:
    row = Release.query.filter_by(id=id).first()
    codeurl = row.url+"include/vdimgck.php"
    resp = res.get(codeurl)
    con = resp.content
    resp1 = Response(con,mimetype="image/jpeg")
    return resp1

@main.route('/child_verify/<id>/',endpoint='child_verify')
def child_verify(id):
  if id:
    row = Releasechild.query.filter_by(id=id).first()
    codeurl = row.url+"include/vdimgck.php"
    resp = res.get(codeurl)
    con = resp.content
    resp1 = Response(con,mimetype="image/jpeg")
    return resp1    